package com.sendpo.zjx.sendpo.fragment;

import android.location.Location;
import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.MyLocationStyle;
import com.sendpo.zjx.sendpo.R;
import com.sendpo.zjx.sendpo.services.AmapLocationService;
import com.shizhefei.view.indicator.IndicatorViewPager;
import com.shizhefei.view.indicator.ScrollIndicatorView;
import com.shizhefei.view.indicator.slidebar.ColorBar;
import com.shizhefei.view.indicator.transition.OnTransitionTextListener;
import com.shizhefei.view.viewpager.SViewPager;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * Created by zjx on 2018
 */

public class WatchStoreMainFragment extends BaseMainFragment implements AMapLocationListener {

    @BindView(R.id.content_indicator)
    ScrollIndicatorView contentIndicator;
    @BindView(R.id.sviewpager)
    SViewPager sviewpager;
    @BindView(R.id.city)
    TextView city;
    @BindView(R.id.mapview)
    MapView mapview;
    @BindView(R.id.index_head)
    RelativeLayout indexHead;
    @BindView(R.id.collapsingtoolbarlayout)
    CollapsingToolbarLayout collapsingtoolbarlayout;
    @BindView(R.id.appbar)
    AppBarLayout appbar;


    private View rootView;
    public static String[] titles = {"全部商家", "赠送商家", "新品商家"};

    private IndicatorViewPager indicatorViewPager;
    private AmapLocationService amapLocationService;
    List<BaseWatchStoreFragment> arrayList = new ArrayList();
    private WatchStoreAlllFragment wa1;
    private WatchStoreZensongFragment wa2;
    private  WatchStoreNewFragment wa3;
    private AMap aMap;
    private boolean isFirst=true;
    @Override
    public View initView() {
        View view = View.inflate(mActivity, R.layout.activity_watchstore, null);
        ButterKnife.bind(view, mActivity);
        return view;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        if (rootView == null) {
            rootView = super.onCreateView(inflater, container, savedInstanceState);
            ButterKnife.bind(this, rootView);
            mapview.onCreate(savedInstanceState);
            if(aMap==null){
                aMap=mapview.getMap();
            }
            initComponent();

        }
        return rootView;
    }
    public void onDestroy()
    {
        super.onDestroy();
        this.mapview.onDestroy();
    }



    public void onPause()
    {
        super.onPause();
        this.mapview.onPause();
    }

    public void onResume()
    {
        super.onResume();
        this.mapview.onResume();
    }

    public void onSaveInstanceState(Bundle paramBundle)
    {
        super.onSaveInstanceState(paramBundle);
        this.mapview.onSaveInstanceState(paramBundle);
    }

    private void initComponent() {
        final UiSettings uiSettings =  aMap.getUiSettings();
        uiSettings.setLogoBottomMargin(-50);//隐藏logo
        //开启室内地图
        aMap.showIndoorMap(true);
        //是否开启指南针
        aMap.getUiSettings().setCompassEnabled(false);
        //是否开启定位按钮
        aMap.setMyLocationEnabled(true);
        aMap.getUiSettings().setMyLocationButtonEnabled(false); //显示默认的定位按钮
        aMap.getUiSettings().setScaleControlsEnabled(true);//控制比例尺控件是否显示
        MyLocationStyle myLocationStyle= new MyLocationStyle();//初始化定位蓝点样式类;
        //  MyLocationStyle strokeColor();//设置定位蓝点精度圆圈的边框颜色的方法。
        //设置定位蓝点精度圆圈的填充颜色的方法。
        // myLocationStyle.radiusFillColor(getResources().getColor(R.color.default_theme));
        myLocationStyle.radiusFillColor(getResources().getColor(R.color.translucent));
        myLocationStyle.strokeWidth(0.0f);
        myLocationStyle.strokeColor(getResources().getColor(R.color.translucent));
        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE_NO_CENTER);//连续定位、且将视角移动到地图中心点，定位点依照设备方向旋转，并且会跟随设备移动。（1秒1次定位）如果不设置myLocationType，默认也会执行此种模式。
        myLocationStyle.interval(1000); //设置连续定位模式下的定位间隔，只在连续定位模式下生效，单次定位模式下不会生效。单位为毫秒。
        aMap.setMyLocationStyle(myLocationStyle);//设置定位蓝点的Style
        //aMap.getUiSettings().setMyLocationButtonEnabled(true);设置默认定位按钮是否显示，非必需设置。
        aMap.setMyLocationEnabled(true);// 设置为true表示启动显示定位蓝点，false表示隐藏定位蓝点并不进行定位，默认是false。
        //J监听点击事件
        //aMap.setOnMyLocationChangeListener(this);
        aMap.setTrafficEnabled(true);
        aMap.setMapType(AMap.MAP_TYPE_NORMAL);
        amapLocationService = new AmapLocationService(mActivity);
        amapLocationService.setmLocationOption(getDefaultAmapLocationOptions());
        amapLocationService.registerListener(WatchStoreMainFragment.this);
        amapLocationService.start();
        this.sviewpager.setCanScroll(false);
        this.sviewpager.setOffscreenPageLimit(1);
        this.indicatorViewPager = new IndicatorViewPager(this.contentIndicator, this.sviewpager);
        //点击切换颜色
        indicatorViewPager.setIndicatorOnTransitionListener(new OnTransitionTextListener().setColor(getResources().getColor(R.color.default_theme), getResources().getColor(R.color.default_gray)));
        //颜色块
        ColorBar colorBar = new ColorBar(mActivity, getResources().getColor(R.color.default_theme), 5);
        colorBar.setWidth(120);
        indicatorViewPager.setIndicatorScrollBar(colorBar);
        arrayList.add(wa1 = new WatchStoreAlllFragment());
        arrayList.add(wa2 = new WatchStoreZensongFragment());
        arrayList.add(wa3 = new WatchStoreNewFragment());
        indicatorViewPager.setAdapter(new FragmentIndicatorAdapter(getChildFragmentManager(), arrayList));
    }


    public AMapLocationClientOption getDefaultAmapLocationOptions() {
        AMapLocationClientOption mLocationOption = null;
        if (mLocationOption == null) {
            mLocationOption = new AMapLocationClientOption();
            //设置定位模式为AMapLocationMode.Hight_Accuracy，高精度模式。
            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Battery_Saving);
            mLocationOption.setLocationCacheEnable(true);
            //     mLocationOption.setOnceLocation(true);
            mLocationOption.setOnceLocationLatest(false);
            //设置是否返回地址信息（默认返回地址信息）
            mLocationOption.setNeedAddress(true);
            //设置是否强制刷新WIFI，默认为true，强制刷1新。
            mLocationOption.setWifiScan(true);
            mLocationOption.setInterval(1000);
            //单位是毫秒，默认30000毫秒，建议超时时间不要低于8000毫秒。
            mLocationOption.setHttpTimeOut(20000);
        }
        return mLocationOption;
    }

    @Override
    public void onLocationChanged(final AMapLocation aMapLocation) {
        if (aMapLocation == null) {
            mActivity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    city.setText("无法定位");
                }
            });
            return;
        }

        if(isFirst==true){
            aMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
                    new LatLng(aMapLocation.getLatitude(),aMapLocation.getLongitude()),21));
            isFirst=false;
        }

        mActivity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                city.setText("" + aMapLocation.getCity() + aMapLocation.getDistrict());
            }
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();


    }


    private class FragmentIndicatorAdapter extends IndicatorViewPager.IndicatorFragmentPagerAdapter {
        private List<BaseWatchStoreFragment> fragments;

        public FragmentIndicatorAdapter(FragmentManager fragmentManager, List<BaseWatchStoreFragment> fragments) {
            super(fragmentManager);
            this.fragments = fragments;
        }

        @Override
        public int getCount() {
            return fragments.size();
        }

        @Override
        public View getViewForTab(int position, View convertView, ViewGroup container) {
            if (convertView == null) {
                convertView = View.inflate(mActivity, R.layout.tab_focus, null);
            }
            TextView textView = (TextView) convertView;
            textView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
            textView.setText(titles[position]);
            return textView;
        }

        @Override
        public Fragment getFragmentForPage(int position) {
            return fragments.get(position);
        }
    }

}
